// 1. React核心库
import React, { useState, useEffect } from 'react';

// 2. UI组件库 - 按字母顺序
import { Card, Descriptions, Button, message, Tag, Progress } from 'antd';

// 3. 图标库
import { EditOutlined, ArrowLeftOutlined, MessageOutlined } from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer } from '@ant-design/pro-components';

// 5. 工具库
import { useParams } from '@umijs/max';
import dayjs from 'dayjs';

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { AIConversation } from '@/services/generated';

const ConversationDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [data, setData] = useState<AIConversation | null>(null);
  const [loading, setLoading] = useState(false);

  // 状态映射
  const statusMap = {
    active: { color: 'green', text: '活跃' },
    archived: { color: 'orange', text: '已归档' },
    deleted: { color: 'red', text: '已删除' },
  };

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        await autoLoginInDev();
        const response = await apiClients.aiChat.aiChatConversationsRetrieve({ id: id! });
        setData(response.data);
      } catch (error) {
        message.error('获取对话详情失败');
      } finally {
        setLoading(false);
      }
    };
    if (id) fetchData();
  }, [id]);

  const status = data?.status ? statusMap[data.status as keyof typeof statusMap] : null;

  return (
    <PageContainer
      loading={loading}
      header={{
        title: '对话详情',
        subTitle: data?.title || '加载中...',
      }}
    >
      <Card>
        <Descriptions column={2} bordered>
          <Descriptions.Item label="ID">{data?.id}</Descriptions.Item>
          <Descriptions.Item label="对话标题">{data?.title}</Descriptions.Item>
          
          <Descriptions.Item label="AI模型">
            {data?.ai_model_name ? (
              <Tag color="blue">{data.ai_model_name}</Tag>
            ) : (
              '未设置'
            )}
          </Descriptions.Item>
          
          <Descriptions.Item label="AI角色">
            {data?.ai_role_name ? (
              <Tag color="green">{data.ai_role_name}</Tag>
            ) : (
              '未设置'
            )}
          </Descriptions.Item>
          
          <Descriptions.Item label="状态">
            {status ? (
              <Tag color={status.color}>{status.text}</Tag>
            ) : (
              data?.status || '-'
            )}
          </Descriptions.Item>
          
          <Descriptions.Item label="消息数量">
            <Tag color="purple">{(data?.message_count || 0).toLocaleString()} 条</Tag>
          </Descriptions.Item>
          
          <Descriptions.Item label="Token使用" span={2}>
            <div style={{ width: '100%', maxWidth: 400 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                <span>已使用: {(data?.used_tokens || 0).toLocaleString()} tokens</span>
                <span>{Math.min((Number(data?.used_tokens) || 0) / 10000 * 100, 100).toFixed(1)}%</span>
              </div>
              <Progress
                percent={Math.min((Number(data?.used_tokens) || 0) / 10000 * 100, 100)}
                status="active"
              />
            </div>
          </Descriptions.Item>
          
          <Descriptions.Item label="所有者ID">{data?.owner || '-'}</Descriptions.Item>
          
          <Descriptions.Item label="创建时间">
            {data?.created_at ? dayjs(data.created_at).format('YYYY-MM-DD HH:mm:ss') : '-'}
          </Descriptions.Item>
          
          <Descriptions.Item label="更新时间">
            {data?.updated_at ? dayjs(data.updated_at).format('YYYY-MM-DD HH:mm:ss') : '-'}
          </Descriptions.Item>
          
          <Descriptions.Item label="最后消息时间">
            {data?.last_message_at ? dayjs(data.last_message_at).format('YYYY-MM-DD HH:mm:ss') : '-'}
          </Descriptions.Item>
        </Descriptions>
        
        <div style={{ marginTop: 16 }}>
          <Button 
            type="primary" 
            icon={<MessageOutlined />}
            href={`/ai-chat/conversations/chat/${id}`}
            style={{ marginRight: 8 }}
          >
            开始对话
          </Button>
          <Button 
            icon={<EditOutlined />}
            href={`/ai-chat/conversations/edit/${id}`}
            style={{ marginRight: 8 }}
          >
            编辑
          </Button>
          <Button 
            icon={<ArrowLeftOutlined />}
            href="/ai-chat/conversations"
          >
            返回列表
          </Button>
        </div>
      </Card>
    </PageContainer>
  );
};

export default ConversationDetail;